﻿using DevExpress.Utils;
using DevExpress.XtraEditors;
using DevExpress.XtraTab;
using Lamex.Base;
using Lamex.Interface;
using Lamex.Library;
using Lamex.Library.CommonClass;
using Lamex.SIESystemManager.BLL;
using Lamex.SIESystemManager.ucControls;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.SqlClient;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Xml;


namespace Lamex.SIESystemManager.UI
{
    public partial class FrmBIEOperationData : frmBaseDataForm
    {
        int angle = 0;//旋转角度
        
        PictureBox pic = new PictureBox();
        XtraTabPage Page = new XtraTabPage();
        Bitmap myBmp;//图片定义
        Point mouseDownPoint = new Point(); //记录拖拽过程鼠标位置
        bool isMove = false;    //判断鼠标在picturebox上移动时，是否处于拖拽过程(鼠标左键是否按下)
        int zoomStep = 75;      //缩放步长
        private static Dictionary<string, XtraTabPage> TabPageDic = new Dictionary<string, XtraTabPage>();
        private static Dictionary<string, PictureBox> PictureDic = new Dictionary<string, PictureBox>();
        private static Dictionary<string, Bitmap> BitDic = new Dictionary<string, Bitmap>();
        string drawNum = "";
        public FrmBIEOperationData()
        {
            InitializeComponent();
            InitializeForm();
            this.Load += new EventHandler(FrmBIEOperationData_Load);

        }
        public string IsEdit = "";
        public string KeysName = "";
        protected override void InitializeForm()
        {
            DataSet ds = BaseFactory<B_IE_SJData_Import>.Instance.StanderDataSet();
            gcViewAll.DataSource = ds.Tables[0];
            gcViewNotFinish.DataSource= ds.Tables[1];
            gcViewFinish.DataSource = ds.Tables[2];
            //_SummaryView = new DevGridView(gridView2);
            //gridView2.DoubleClick += new EventHandler(OnGridViewDoubleClick); //主表DoubleClict
            //frmGridViewCust.RegisterGrid(gridView2);
            //DevStyle.SetGridControlLayout(gcView, false);//表格设置   

            //DevStyle.SetSummaryGridViewLayout(gridView2);
            //DevStyle.SetDetailGridViewLayout(gridView2);
            ShowSummary(); //下载显示数据.
            //tpSummary = xtraTabPage1;
            //tcBusiness = xtraTabControl1;
            //tpSummary.PageVisible = true;
            ////tpDetail.PageVisible = false;
            //tcBusiness.ShowTabHeader = DefaultBoolean.True;
            //tcBusiness.SelectedTabPage = tpSummary;
            //ShowSummaryPage(true); //一切初始化完毕後显示SummaryPage     
            ucAutoAddControls1.GetTableInfo();
        }
        private void FrmBIEOperationData_Load(object sender, EventArgs e)
        {
            try { this.InitButtons(); } catch { }//初始化标准功能，因要应用于RibbonForm，所以加入异常处理
        }
        private void ShowSummary()
        {
            try
            {
                //
                //ucLookUpEdit1.ValueMember = "UserName";
                //ucLookUpEdit1.DisPlayMember = "UserName";
                //ucLookUpEdit1.DataSource = dt;
                ////ucLookUpEdit1.UcPopulateColumns();

                ////ucLookUpEdit1.Item[1].Caption = "用户名称";
                //////ucLookUpEdit1.ForceInitialize();
                ////ucLookUpEdit1.UcItemIndex = 0;
                //DoBindingSummaryGrid(dt); //绑定主表的Grid
                //ShowSummaryPage(true); //显示Summary页面. 
                xtraTabPage2.PageEnabled = false;
                xtraTabPage1.PageEnabled = true;

            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
        /// <summary>
        /// 新增
        /// </summary>
        /// <param name="sender"></param>
        public override void DoAdd(Lamex.Interface.IButtonInfo sender)
        {
            #region 按钮权限
            if (!BuildSqlHelper.IsExistList("B_IE_Operational_Definition", "LamexMESManager")) return;
            #endregion
            xtraTabPage1.PageEnabled = false;
            xtraTabPage2.PageEnabled = true;
            xtraTabPage2.PageVisible = true;
            IsEdit = "新增";
            xtraTabPage2.Tag = "新增";
            base.DoAdd(sender);
            txtEditDRAWING_NUMBER.Focus();
        }
        /// <summary>
        /// 查询
        /// </summary>
        /// <param name="sender"></param>
        public override void DoView(Lamex.Interface.IButtonInfo sender)
        {
            base.DoView(sender);

        }
        /// <summary>
        /// 删除
        /// </summary>
        /// <param name="sender"></param>
        public override void DoDelete(Lamex.Interface.IButtonInfo sender)
        {
         
            base.DoDelete(sender);
        }
        private void txtEditDRAWING_NUMBER_KeyDown(object sender, KeyEventArgs e)
        {         
            ucAutoAddControls1.Claer();
            ucAutoAddControls1.DrawingNumber = txtEditDRAWING_NUMBER.Text;
            ucAutoAddControls1.userName = Lamex.Common.Loginer.CurrentUser.Account;
        }

        #region 图纸缩放平移
        //鼠标按下功能
        private void pic_MouseDown(object sender, MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Left)
            {
                mouseDownPoint.X = Cursor.Position.X;
                mouseDownPoint.Y = Cursor.Position.Y;
                isMove = true;
                pic.Focus();//
            }
        }
        //松开鼠标
        private void pic_MouseUp(object sender, MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Left)
            {
                isMove = false;
            }
        }
        //鼠标移动
        private void pic_MouseMove(object sender, MouseEventArgs e)
        {
            pic.Focus();//
            if (isMove)
            {
                int x, y;
                int moveX, moveY;
                moveX = Cursor.Position.X - mouseDownPoint.X;
                moveY = Cursor.Position.Y - mouseDownPoint.Y;
                x = pic.Location.X + moveX;
                y = pic.Location.Y + moveY;
                pic.Location = new Point(x, y);
                mouseDownPoint.X = Cursor.Position.X;
                mouseDownPoint.Y = Cursor.Position.Y;
            }
        }
        //鼠标滚轮滚动功能
        private void pic_MouseWheel(object sender, MouseEventArgs e)
        {
            int x = e.Location.X;
            int y = e.Location.Y;
            int ow = pic.Width;
            int oh = pic.Height;
            int VX, VY;
            if (e.Delta > 0)
            {
                pic.Width += zoomStep;
                pic.Height += zoomStep;

                PropertyInfo pInfo = pic.GetType().GetProperty("ImageRectangle", BindingFlags.Instance |
                    BindingFlags.NonPublic);
                Rectangle rect = (Rectangle)pInfo.GetValue(pic, null);

                pic.Width = rect.Width;
                pic.Height = rect.Height;
            }
            if (e.Delta < 0)
            {

                if (pic.Width < myBmp.Width / 10)
                    return;

                pic.Width -= zoomStep;
                pic.Height -= zoomStep;
                PropertyInfo pInfo = pic.GetType().GetProperty("ImageRectangle", BindingFlags.Instance |
                    BindingFlags.NonPublic);
                Rectangle rect = (Rectangle)pInfo.GetValue(pic, null);
                pic.Width = rect.Width;
                pic.Height = rect.Height;
            }

            VX = (int)((double)x * (ow - pic.Width) / ow);
            VY = (int)((double)y * (oh - pic.Height) / oh);
            pic.Location = new Point(pic.Location.X + VX, pic.Location.Y + VY);

        }
        private void Page_MouseDown(object sender, MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Left)
            {
                mouseDownPoint.X = Cursor.Position.X;
                mouseDownPoint.Y = Cursor.Position.Y;
                isMove = true;
            }
        }

        private void Page_MouseUp(object sender, MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Left)
            {
                isMove = false;
            }
        }

        private void Page_MouseMove(object sender, MouseEventArgs e)
        {

            Page.Focus();
            if (isMove)
            {
                int x, y;
                int moveX, moveY;
                moveX = Cursor.Position.X - mouseDownPoint.X;
                moveY = Cursor.Position.Y - mouseDownPoint.Y;
                x = pic.Location.X + moveX;
                y = pic.Location.Y + moveY;
                pic.Location = new Point(x, y);
                mouseDownPoint.X = Cursor.Position.X;
                mouseDownPoint.Y = Cursor.Position.Y;
            }
        }
        #endregion

        #region 动态生成Tab页和图片
        /// <summary>
        /// 新增选项卡页
        /// </summary>
        /// <param name="tabControl">选项卡控件</param>
        /// <param name="tabPageName">当期选项卡页name名称</param>
        /// <param name="tabText">当前选项卡页Text标题</param>
        /// <param name="newFormName">当前选项卡中的新窗体</param>
        public void AddTabpage(XtraTabControl tabControl, string tabPageName, string tabText, string newFormName, string pictureName)
        {
            if (IsTabpageExsit(tabControl, tabPageName))
            {
                return;
            }
            Page = new XtraTabPage();
            Page.Name = tabPageName;
            Page.Text = tabText;
            Page.Tooltip = tabPageName;

            Page.Controls.Add(AddNewForm(newFormName, pictureName));
            tabControl.TabPages.Add(Page);
            TabPageDic.Add(tabPageName, Page);
            tabControl.SelectedTabPage = Page;
            //Page.Controls.Add(AddNewForm(newFormName));
        }
        /// <summary>
        /// 判断选项卡是否已经存在
        /// </summary>
        /// <param name="tabControl">选项卡控件</param>
        /// <param name="tabPageName">选项卡名称</param>
        /// <returns></returns>
        private bool IsTabpageExsit(XtraTabControl tabControl, string tabPageName)
        {
            foreach (var item in TabPageDic)
            {
                if (item.Key == tabPageName)
                {
                    tabControl.SelectedTabPage = item.Value;
                    return true;
                }
            }
            return false;
        }
        /// <summary>
        /// 在选项卡中生成图片
        /// </summary>
        /// <param name="form">图片名称</param>
        private PictureBox AddNewForm(string formName, string pictureName)
        {
            pic = new PictureBox();
            if (pictureName != "")
            {
                string filename = pictureName;
                myBmp = new Bitmap(filename);
                pic.Name = formName;
                pic.Location = new System.Drawing.Point(100, 4);//5,4
                pic.Size = new System.Drawing.Size(980, 410);//100,50
                pic.TabIndex = 0;
                pic.TabStop = false;
                pic.Image = myBmp;
                pic.SizeMode = PictureBoxSizeMode.Zoom; //设置picturebox为缩放模式Zoom
                //pic.Width = 1033;//myBmp.Width;
                //pic.Height = 358;//myBmp.Height;
                PictureDic.Add(formName, pic);
                BitDic.Add(formName, myBmp);

            }
            return pic;
        }
        #endregion

        //刷新
        public void ReFresh()
        {
            txtEditDRAWING_NUMBER.Text = "";
            txtEditNUMBER1.Text = "";
            txtEditNUMBER2.Text = "";
            txtEditNUMBER3.Text = "";
            txtEditNUMBER4.Text = "";
            txtEditNUMBER5.Text = "";
            txtEditNUMBER6.Text = "";
            txtEditNUMBER7.Text = "";
            txtEditNUMBER8.Text = "";
            txtEditNUMBER9.Text = "";
            txtEditNUMBER10.Text = "";
            gridControl1.DataSource = new DataTable();
            txtEditDRAWING_NUMBER.Focus();
        }

        private void xtraTabControl2_SelectedPageChanged(object sender, DevExpress.XtraTab.TabPageChangedEventArgs e)
        {
            XtraTabPage Page = xtraTabControl2.SelectedTabPage;
            if (Page == null)
                return;
            foreach (var item in PictureDic)
            {
                if (item.Key.Substring(item.Key.Length - 1, 1) == Page.Name.Substring(Page.Name.Length - 1, 1))
                {
                    pic = PictureDic[item.Key];
                }
            }
            pic.MouseDown += new System.Windows.Forms.MouseEventHandler(pic_MouseDown);
            pic.MouseMove += new System.Windows.Forms.MouseEventHandler(pic_MouseMove);
            pic.MouseUp += new System.Windows.Forms.MouseEventHandler(pic_MouseUp);
            pic.MouseWheel += new MouseEventHandler(pic_MouseWheel);
            Page.MouseDown += new System.Windows.Forms.MouseEventHandler(Page_MouseDown);
            Page.MouseUp += new System.Windows.Forms.MouseEventHandler(Page_MouseUp);
            Page.MouseMove += new System.Windows.Forms.MouseEventHandler(Page_MouseMove);

            #region 动态生成旋转按钮
            Page = xtraTabControl2.SelectedTabPage;
            if (Page == null)
                return;

            Button btn = new Button();
            Image clo = Image.FromFile(System.Windows.Forms.Application.StartupPath + "\\image\\left.ico");
            btn.Image = clo;
            btn.BackgroundImageLayout = System.Windows.Forms.ImageLayout.Zoom;
            btn.BackColor = System.Drawing.Color.Transparent;
            btn.Name = "ClockwiseBtn";
            btn.Size = new Size(47, 36);
            btn.Location = new Point(5, 350);
            Page.Controls.Add(btn);
            btn.Click += new EventHandler(aBtn_Click);

            Button btn2 = new Button();
            Image ant = Image.FromFile(System.Windows.Forms.Application.StartupPath + "\\image\\right.ico");
            btn2.Image = ant;
            btn2.BackgroundImageLayout = System.Windows.Forms.ImageLayout.Zoom;
            btn2.BackColor = System.Drawing.Color.Transparent;
            btn2.Name = "AntiClockwiseBtn";
            btn2.Size = new System.Drawing.Size(47, 36);
            btn2.Location = new System.Drawing.Point(5, 388);
            Page.Controls.Add(btn2);
            btn2.Click += new EventHandler(aBtn2_Click);
            #endregion
        }

        public override void DoReturn(Lamex.Interface.IButtonInfo sender)
        {
            if (!string.IsNullOrEmpty(drawNum))
            {
                string sql = "";
                sql = @"update B_IE_SJData_Import set locked=0 where DRAWING_NO_STANDARD='" + drawNum + "'";
                int m = BaseBuildSql.ExecuteNonQuery(sql);
            }
            base.DoReturn(sender);
        }

        #region"加载控件"
        DevExpress.XtraEditors.TextEdit editControl = null;
        string workProcess = "";
        public void LoadItem(DevExpress.XtraEditors.TextEdit textEdit)
        {
            if (string.IsNullOrEmpty(txtEditDRAWING_NUMBER.Text))
            {
                XtraMessageBox.Show("图纸号为空，无法加载项目");
                return;
            }
            string[] strArr = textEdit.Text.Split('_');
            if (strArr.Count() > 0)
            {
                editControl = textEdit;
                workProcess = strArr[0];
                ucAutoAddControls1.LoadListImtes(strArr[0], editControl, txtEditDRAWING_NUMBER.Text);
                ucAutoAddControls1.LoadData(txtEditDRAWING_NUMBER.Text, Lamex.Common.Loginer.CurrentUser.Account, DateTime.Now.ToString(), workProcess, editControl,"");
            }
        }

        private void txtEditNUMBER1_Click(object sender, EventArgs e)
        {
            LoadItem(txtEditNUMBER1);
        }
        private void txtEditNUMBER2_Click(object sender, EventArgs e)
        {
            LoadItem(txtEditNUMBER2);
        }

        private void txtEditNUMBER3_Click(object sender, EventArgs e)
        {
            LoadItem(txtEditNUMBER3);
        }

        private void txtEditNUMBER4_Click(object sender, EventArgs e)
        {
            LoadItem(txtEditNUMBER4);
        }

        private void txtEditNUMBER5_Click(object sender, EventArgs e)
        {
            LoadItem(txtEditNUMBER5);
        }

        private void txtEditNUMBER6_Click(object sender, EventArgs e)
        {
            LoadItem(txtEditNUMBER6);
        }

        private void txtEditNUMBER7_Click(object sender, EventArgs e)
        {
            LoadItem(txtEditNUMBER7);
        }

        private void txtEditNUMBER8_Click(object sender, EventArgs e)
        {
            LoadItem(txtEditNUMBER8);
        }

        private void txtEditNUMBER9_Click(object sender, EventArgs e)
        {
            LoadItem(txtEditNUMBER9);
        }

        private void txtEditNUMBER10_Click(object sender, EventArgs e)
        {
            LoadItem(txtEditNUMBER10);
        }

        private void txtEditNUMBER11_Click(object sender, EventArgs e)
        {
            LoadItem(txtEditNUMBER11);
        }

        private void txtEditNUMBER12_Click(object sender, EventArgs e)
        {
            LoadItem(txtEditNUMBER12);
        }

        private void txtEditNUMBER13_Click(object sender, EventArgs e)
        {
            LoadItem(txtEditNUMBER13);
        }
        #endregion
        private void simpleButton1_Click(object sender, EventArgs e)
        {
            ucAutoAddControls1.Save(txtEditDRAWING_NUMBER.Text, Lamex.Common.Loginer.CurrentUser.Account, DateTime.Now.ToString(), workProcess, editControl);
        }

        public override void DoSave(Lamex.Interface.IButtonInfo sender)
        {
            #region 按钮权限
            if (!BuildSqlHelper.IsExistList("B_IE_Operation_Data", "LamexMESManager")) return;
            #endregion
            if (string.IsNullOrEmpty(txtEditDRAWING_NUMBER.Text))
            {
                XtraMessageBox.Show("图纸号为空，无法加载项目");
                return;
            }
            List<string> strProcessList = new List<string>();
            foreach (Control c in panelControl9.Controls)
            {
                if (c is TextEdit)
                {
                    TextEdit t = c as TextEdit;
                    if (c.Name != "txtEditDRAWING_NUMBER")
                    {
                        //if(c.Enabled==true)
                        //{
                            string[] arrItems = c.Text.Split('_');
                            strProcessList.Add(arrItems[0]);
                        //}
                    }
                }
            }
            if (ucAutoAddControls1.SaveAllList(txtEditDRAWING_NUMBER.Text, strProcessList))
            {
                xtraTabPage2.PageEnabled = false;
                xtraTabPage1.PageEnabled = true;
                gridControl1.DataSource = null;
                xtraTabControl2.TabPages.Clear();
                foreach (Control c in panelControl9.Controls)
                {
                    if (c is TextEdit)
                    {
                        TextEdit t = c as TextEdit;
                        t.Text = "";
                        t.Enabled = true;

                    }
                }
                XtraMessageBox.Show("保存成功！");
                InitializeForm();
            }
            base.DoSave(sender);
        }

        private void txtEditDRAWING_NUMBER_EditValueChanged(object sender, EventArgs e)
        {


        }

        private void txtEditNUMBER1_Leave(object sender, EventArgs e)
        {

        }
        
        //private void (object sender, EventArgs e)
        //{

        private void txtEditNUMBER1_TabIndexChanged(object sender, EventArgs e)
        {

        }

        private void txtEditNUMBER7_TabIndexChanged(object sender, EventArgs e)
        {

        }

        private void txtEditNUMBER6_Leave(object sender, EventArgs e)
        {
            //ucAutoAddControls.Save(txtEditDRAWING_NUMBER.Text, Lamex.Common.Loginer.CurrentUser.Account, DateTime.Now.ToString(), workProcess, editControl);
        }

        private void txtEditNUMBER7_Leave(object sender, EventArgs e)
        {
            //ucAutoAddControls1.Save(txtEditDRAWING_NUMBER.Text, Lamex.Common.Loginer.CurrentUser.Account, DateTime.Now.ToString(), workProcess, editControl);
        }

        private void txtEditDRAWING_NUMBER_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (e.KeyChar == (char)13)
            {
                Search();
            }
            
        }
        private void Search()
        {
            foreach (Control c in panelControl9.Controls)
            {
                if (c is TextEdit)
                {
                    TextEdit t = c as TextEdit;
                    if (c.Name != "txtEditDRAWING_NUMBER")
                    {
                        t.Enabled = true;
                        t.BackColor = Color.White;
                        t.Properties.ReadOnly = false;
                        t.Text = "";


                    }
                }
            }

            #region 根据图纸号查询
            string sqlWhere = "";
            string sql = " select * from VIEW_DRAWING_DATA where 1=1 ";
            if (!string.IsNullOrEmpty(txtEditDRAWING_NUMBER.Text))
            {
                sqlWhere += " and Drawing_Num = '" + txtEditDRAWING_NUMBER.Text + "'";
            }
            else
            {
                DevExpress.XtraEditors.XtraMessageBox.Show("请输入图纸编号", "提示", MessageBoxButtons.OK);
                return;
            }
            sql = sql + sqlWhere;
            DataTable dt = BaseBuildSql.GetDataTableBySql(sql);
            if (dt.Rows.Count > 0)
            {
                //取一行即可
                txtEditNUMBER1.Text = dt.Rows[0]["Procedure_01"].ToString() == "x" ? "" : dt.Rows[0]["Procedure_01"].ToString();
                txtEditNUMBER2.Text = dt.Rows[0]["Procedure_02"].ToString() == "x" ? "" : dt.Rows[0]["Procedure_02"].ToString();
                txtEditNUMBER3.Text = dt.Rows[0]["Procedure_03"].ToString() == "x" ? "" : dt.Rows[0]["Procedure_03"].ToString();
                txtEditNUMBER4.Text = dt.Rows[0]["Procedure_04"].ToString() == "x" ? "" : dt.Rows[0]["Procedure_04"].ToString();
                txtEditNUMBER5.Text = dt.Rows[0]["Procedure_05"].ToString() == "x" ? "" : dt.Rows[0]["Procedure_05"].ToString();
                txtEditNUMBER6.Text = dt.Rows[0]["Procedure_06"].ToString() == "x" ? "" : dt.Rows[0]["Procedure_06"].ToString();
                txtEditNUMBER7.Text = dt.Rows[0]["Procedure_07"].ToString() == "x" ? "" : dt.Rows[0]["Procedure_07"].ToString();
                txtEditNUMBER8.Text = dt.Rows[0]["Procedure_08"].ToString() == "x" ? "" : dt.Rows[0]["Procedure_08"].ToString();
                txtEditNUMBER9.Text = dt.Rows[0]["Procedure_09"].ToString() == "x" ? "" : dt.Rows[0]["Procedure_09"].ToString();
                txtEditNUMBER10.Text = dt.Rows[0]["Procedure_10"].ToString() == "x" ? "" : dt.Rows[0]["Procedure_10"].ToString();
                //string strList = "";
                //foreach (DataRow dr in dt.Rows)
                //{
                //    strList += dr["PartNumber"].ToString() + ";";
                //}
                ////ucAutoAddControls.strPartNumber = strList;
            
                gridControl1.DataSource = dt;
            }
            else
            {
                DevExpress.XtraEditors.XtraMessageBox.Show("该图纸号不存在", "提示", MessageBoxButtons.OK);
                ReFresh();
                return;
            }
            #endregion
            #region 加载图片
            #region 清空控件值
            int tabCount = this.xtraTabControl2.TabPages.Count;

            for (int i = tabCount - 1; i >= 0; i--)
            {

                this.xtraTabControl2.TabPages.RemoveAt(i);

            }
            Page = new XtraTabPage();
            pic = new PictureBox();
            TabPageDic = new Dictionary<string, XtraTabPage>();
            PictureDic = new Dictionary<string, PictureBox>();
            BitDic = new Dictionary<string, Bitmap>();
            #endregion
            int Num = 0;
            int Count = 0;
            string pictureName = txtEditDRAWING_NUMBER.Text;
            List<string> pictureNames = new List<string>();
            string filename = "",filenameTemp="";// @定义标准图片路径和临时图片路径
            #region XML配置图片路径
            XmlDocument doc = new XmlDocument();
            doc.Load(Application.StartupPath + "\\PicturePathConfig.xml");
            XmlNode xn = doc.SelectSingleNode("Pictures");
            XmlNodeList xnl = xn.ChildNodes;
            foreach (XmlNode xn1 in xnl)
            {
                XmlElement xe = (XmlElement)xn1;
                XmlNodeList xn2 = xe.ChildNodes;
                filename = xn2.Item(0).InnerText;//读取标准图片路径
                Count = Convert.ToInt32(xn2.Item(1).InnerText);//读取张数
                filenameTemp = xn2.Item(3).InnerText;//读取临时图片路径
            }
            //定位到具体图纸（默认10张，可以通过xml配置）
            for (int i = 0; i < Count; i++)
            {

                string picTemp = "";
                if (i == 0)
                {
                    picTemp = filename + pictureName + ".tif";
                }
                else
                {
                    picTemp = filename + pictureName + "-" + i + ".tif";
                }
                if (!File.Exists(picTemp))
                {
                    continue;
                }
                pictureNames.Add(picTemp);
                Num++;
            }
            //临时图片
            for (int i = 0; i < Count; i++)
            {

                string picTemp = "";
                if (i == 0)
                {
                    picTemp = filenameTemp + pictureName + ".tif";
                }
                else
                {
                    picTemp = filenameTemp + pictureName + "-" + i + ".tif";
                }
                if (!File.Exists(picTemp))
                {
                    continue;
                }
                pictureNames.Add(picTemp);
                Num++;
            }
            #endregion

            for (int i = 0; i < Num; i++)
            {

                AddTabpage(xtraTabControl2, "xtrPage" + (i + 1), "第" + (i + 1) + "张", "pictureBox" + (i + 1), pictureNames[i].ToString());

            }
            xtraTabControl2.SelectedTabPageIndex = 0;//默认选中第一页
            #endregion
            foreach (Control c in panelControl9.Controls)
            {
                if (c is TextEdit)
                {
                    if (c.Name != "txtEditDRAWING_NUMBER")
                    {

                        if (string.IsNullOrEmpty(c.Text))
                        {
                            TextEdit t = c as TextEdit;
                            t.Enabled = false;
                            t.Properties.ReadOnly = true;
                            t.BackColor = Color.LightGray;

                        }

                    }
                }
            }
            ucAutoAddControls1.Claer();
            ucAutoAddControls1.DrawingNumber = txtEditDRAWING_NUMBER.Text;
            ucAutoAddControls1.userName = Lamex.Common.Loginer.CurrentUser.Account;
            foreach (Control c in panelControl9.Controls)
            {
                if (c is TextEdit)
                {
                    if ("txtEditDRAWING_NUMBER" != c.Name)
                    {
                        string[] strArr = c.Text.Split('_');
                        if (strArr.Count() > 0)
                        {
                            editControl = c as TextEdit;
                            workProcess = strArr[0];
                            ucAutoAddControls1.LoadDataType(txtEditDRAWING_NUMBER.Text, Lamex.Common.Loginer.CurrentUser.Account, DateTime.Now.ToString(), workProcess, editControl);
                        }
                    }

                }

            }
            #region 增加版本检查-若图纸有旧版本则直接带数据出来
            Calculate.GetOperation_Version.Get_Version_Values(txtEditDRAWING_NUMBER.Text);
            #endregion
            string sql2 = @"update B_IE_SJData_Import set Flag=1,CREATE_TIME=GETDATE(),LockMan='"+ Lamex.Common.Loginer.CurrentUser.Account + "',Locked=1 where DRAWING_NO_STANDARD='" + txtEditDRAWING_NUMBER.Text + "'";
            BaseFactory<B_IE_SJData_Import>.Instance.ExecuteNonQuery(sql2);
        }
        private void aBtn_Click(object sender, EventArgs e)
        {
            angle += 90;//每次增加90度
            XtraTabPage Page = xtraTabControl2.SelectedTabPage;
            if (Page == null)
                return;
            foreach (var item in PictureDic)
            {
                if (item.Key.Substring(item.Key.Length - 1, 1) == Page.Name.Substring(Page.Name.Length - 1, 1))
                {
                    pic = PictureDic[item.Key];
                    foreach (var bmp in BitDic)
                    {
                        if (item.Key.Substring(item.Key.Length - 1, 1) == Page.Name.Substring(Page.Name.Length - 1, 1))
                        {
                            myBmp = BitDic[item.Key];
                            pic.Image = picRotate(myBmp, angle);//将旋转后的图片设置为picturebox背景
                        }
                    }

                }
            }

            //顺时针旋转

            if (angle >= 360)
            {
                angle = 0;
            }

            GC.Collect();
        }
        private void aBtn2_Click(object sender, EventArgs e)
        {
            angle -= 90;//每次减少90度
            if (angle == 0)
            {
                angle = 360;
            }
            if (angle < 0)
            {
                angle = 270;
            }

            XtraTabPage Page = xtraTabControl2.SelectedTabPage;
            if (Page == null)
                return;
            foreach (var item in PictureDic)
            {
                if (item.Key.Substring(item.Key.Length - 1, 1) == Page.Name.Substring(Page.Name.Length - 1, 1))
                {
                    pic = PictureDic[item.Key];
                    foreach (var bmp in BitDic)
                    {
                        if (item.Key.Substring(item.Key.Length - 1, 1) == Page.Name.Substring(Page.Name.Length - 1, 1))
                        {
                            myBmp = BitDic[item.Key];
                            pic.Image = picRotate(myBmp, angle);//将旋转后的图片设置为picturebox背景
                        }
                    }

                }
            }
            GC.Collect();
        }
        //使图片旋转的方法
        public static Bitmap picRotate(Bitmap b, int angle)
        {

            angle = angle % 360;            //弧度转换
            double radian = angle * Math.PI / 180.0;
            double cos = Math.Cos(radian);
            double sin = Math.Sin(radian);
            //原图的宽和高
            int w = b.Width;
            int h = b.Height;
            int W = (int)(Math.Max(Math.Abs(w * cos - h * sin), Math.Abs(w * cos + h * sin)));
            int H = (int)(Math.Max(Math.Abs(w * sin - h * cos), Math.Abs(w * sin + h * cos)));
            //目标位图
            // Image dsImage = new Bitmap(W, H);
            Bitmap dsImage = new Bitmap(W, H);
            System.Drawing.Graphics g = System.Drawing.Graphics.FromImage(dsImage);
            g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.Bilinear;
            g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
            //计算偏移量
            Point Offset = new Point((W - w) / 2, (H - h) / 2);
            //构造图像显示区域：让图像的中心与窗口的中心点一致
            Rectangle rect = new Rectangle(Offset.X, Offset.Y, w, h);
            Point center = new Point(rect.X + rect.Width / 2, rect.Y + rect.Height / 2);
            g.TranslateTransform(center.X, center.Y);
            g.RotateTransform(360 - angle);
            //恢复图像在水平和垂直方向的平移
            g.TranslateTransform(-center.X, -center.Y);
            g.DrawImage(b, rect);
            //重至绘图的所有变换
            g.ResetTransform();
            g.Save();
            g.Dispose();
            //dsImage.Save("yuancd.jpg", System.Drawing.Imaging.ImageFormat.Jpeg);
            // g.DrawImage(b, new Point(0, 0));
            return dsImage;
        }

        private void gcViewAll_DoubleClick(object sender, EventArgs e)
        {
            
        }
            
        private void uceditKeyPress_UcTextKeyPress(object sender, KeyPressEventArgs e)
        {
            if (e.KeyChar == 13)
            {
                if (!string.IsNullOrEmpty(uceditKeyPress.Text))
                {
                    if (BaseFactory<B_IE_SJData_Import>.Instance.IsExistDrawRecord(uceditKeyPress.Text) < 0) return;
                    string sql = @"insert into B_IE_SJData_Import(
                       [DRAWING_NO_SJ]
                      ,[DRAWING_NO_STANDARD]
                      ,[CREATE_TIME]
                      ,[Flag])
                       values('','" + uceditKeyPress.Text + "',GETDATE(),0)";

                    if (BaseFactory<B_IE_SJData_Import>.Instance.ImportDrawRecord(uceditKeyPress.Text.Trim()) <= 0)
                    {
                        if (BaseFactory<B_IE_SJData_Import>.Instance.ExecuteNonQuery(sql) > 0)
                        {
                            InitializeForm();
                        }
                    }
                }
                if (gridView2.RowCount < 0) return;
                for (int i= 0; i < gridView2.RowCount;i++)
                {

                    if (uceditKeyPress.Text.Trim() == gridView2.GetRowCellDisplayText(i, "DRAWING_NO_STANDARD").ToString())
                    {
                        gridView2.FocusedRowHandle = i;
                        

                    }

                }
                for (int i = 0; i < gridView3.RowCount; i++)
                {
                    if (uceditKeyPress.Text.Trim() == gridView3.GetRowCellDisplayText(i, "DRAWING_NO_STANDARD").ToString())
                    {
                        gridView3.FocusedRowHandle = i;
                        //gridView2.

                    }

                }
                for (int i = 0; i < gridView4.RowCount; i++)
                {
                    if (uceditKeyPress.Text.Trim() == gridView4.GetRowCellDisplayText(i, "DRAWING_NO_STANDARD").ToString())
                    {
                        gridView4.FocusedRowHandle = i;

                    }

                }
            }
        }

        private void gcViewNotFinish_DoubleClick(object sender, EventArgs e)
        {
            int iRow = gridView3.FocusedRowHandle;
            txtEditDRAWING_NUMBER.Text = gridView3.GetRowCellDisplayText(iRow, "DRAWING_NO_STANDARD").ToString();
            drawNum = txtEditDRAWING_NUMBER.Text;
            string sql = @"select * from  B_IE_SJData_Import  where DRAWING_NO_STANDARD='" + gridView3.GetRowCellDisplayText(iRow, "DRAWING_NO_STANDARD").ToString() + "' and Locked=1 ";
            
            string sql2 = @"select * from  B_IE_SJData_Import  where DRAWING_NO_STANDARD='" + gridView3.GetRowCellDisplayText(iRow, "DRAWING_NO_STANDARD").ToString() + "' and Locked=1 and LockMan='" + Lamex.Common.Loginer.CurrentUser.Account + "'";

            DataTable dt = BaseFactory<B_IE_SJData_Import>.Instance.GetDataTableBySql(sql);
            DataTable dt2 = BaseFactory<B_IE_SJData_Import>.Instance.GetDataTableBySql(sql2);
            if (dt2.Rows.Count > 0)
            {
                xtraTabPage2.PageEnabled = true;
                xtraTabPage1.PageEnabled = false;
                Search();
            }
            else
            {
                if (dt.Rows.Count > 0)
                {
                    string name = dt.Rows[0]["LockMan"].ToString();
                    XtraMessageBox.Show("录入员-" + name + "：正在操作此图纸号");
                    return;
                }
                xtraTabPage2.PageEnabled = true;
                xtraTabPage1.PageEnabled = false;
                Search();
            }
        }

        private void gcViewFinish_DoubleClick(object sender, EventArgs e)
        {
            int iRow = gridView4.FocusedRowHandle;
            txtEditDRAWING_NUMBER.Text = gridView4.GetRowCellDisplayText(iRow, "DRAWING_NO_STANDARD").ToString();
            drawNum = txtEditDRAWING_NUMBER.Text;
            string sql = @"select * from  B_IE_SJData_Import  where DRAWING_NO_STANDARD='" + gridView4.GetRowCellDisplayText(iRow, "DRAWING_NO_STANDARD").ToString() + "' and Locked=1 ";
            string sql2 = @"select * from  B_IE_SJData_Import  where DRAWING_NO_STANDARD='" + gridView4.GetRowCellDisplayText(iRow, "DRAWING_NO_STANDARD").ToString() + "' and Locked=1 and LockMan='"+ Lamex.Common.Loginer.CurrentUser.Account + "'  ";

            DataTable dt = BaseFactory<B_IE_SJData_Import>.Instance.GetDataTableBySql(sql);
            DataTable dt2 = BaseFactory<B_IE_SJData_Import>.Instance.GetDataTableBySql(sql2);
            if (dt2.Rows.Count > 0)
            {
                xtraTabPage2.PageEnabled = true;
                xtraTabPage1.PageEnabled = false;
                Search();
            }
            else
            {
                if (dt.Rows.Count > 0)
                {
                    string name = dt.Rows[0]["LockMan"].ToString();
                    XtraMessageBox.Show("录入员-" + name + "：正在操作此图纸号");
                    return;
                }
                xtraTabPage2.PageEnabled = true;
                xtraTabPage1.PageEnabled = false;
                Search();
            }
        }

        private void btnImport_Click(object sender, EventArgs e)
        {
            #region 按钮权限
            if (!BuildSqlHelper.IsExistList("B_IE_SJData_Import", "LamexMESManager")) return;
            #endregion
            FrmImport frm = new FrmImport("B_IE_SJData_Import");
            frm.ShowDialog();
            InitializeForm();

        }
        string DrawNumdelete = "";
        private void gcViewAll_Click(object sender, EventArgs e)
        {
            if (gridView2.RowCount < 0) return;
            int iRow = gridView2.FocusedRowHandle;
            DrawNumdelete = gridView2.GetRowCellDisplayText(iRow, "IDNO").ToString();
        }

        private void ToolStripMenuItemdelete_Click(object sender, EventArgs e)
        {
            if(string.IsNullOrEmpty(DrawNumdelete))
            {
                XtraMessageBox.Show("没选中要选除的数据！");
                return;
            }
            if(BaseFactory<B_IE_SJData_Import>.Instance.Delete(DrawNumdelete))
            {
                XtraMessageBox.Show("删除成功！");
                InitializeForm();
            }
            else
            {
                XtraMessageBox.Show("删除失败！");
            }

        }

        private void simpleButton1_Click_1(object sender, EventArgs e)
        {
            #region 按钮权限
            if (!BuildSqlHelper.IsExistList("B_IE_SJData_Import", "LamexMESManager")) return;
            #endregion
            if (gridView2.RowCount == 0) return;
            if (DialogResult.No == XtraMessageBox.Show("是否要批量删除", "提示", MessageBoxButtons.YesNo, MessageBoxIcon.Question)) return;
            string strSeprator = "";
            for (int i=0;i<gridView2.RowCount;i++)
            {
                if(gridView2.GetRowCellDisplayText(i, "Flag")== "Checked")
                {
                    strSeprator += gridView2.GetRowCellDisplayText(i, "IDNO") + ",";
                }
            }

            List<string> lst = new List<string>();
            lst.Add("B_IE_SJData_Import");
            //lst.Add(txtPartNum.Text.ToString());
            lst.Add("IDNO");
            lst.Add(strSeprator);
            lst.Add(",");
            SqlParameter outputValue = new SqlParameter();
            SqlParameter returnValue = new SqlParameter();
            int m = Lamex.Base.BaseBuildSql.GetReturnValueExecute("BatchDeleteFlagList", lst, ref outputValue, ref returnValue);
            if (m > 0)
            {
                XtraMessageBox.Show(outputValue.Value.ToString());
                List<Model.B_IE_SJData_ImportInfo> ls = BaseFactory<B_IE_SJData_Import>.Instance.GetEntriyList(" 1=1 and isnull(DRAWING_NO_SJ,'')='' and deleted !=1 order by CREATE_TIME desc");
                gcViewAll .DataSource = ls;
            }
            else
                XtraMessageBox.Show(outputValue.Value.ToString());
        }
        public override void DoImport(IButtonInfo sender)
        {
            #region 按钮权限
            if (!BuildSqlHelper.IsExistList("B_IE_Operation_Data", "LamexMESManager")) return;
            #endregion
            FrmImport frm = new FrmImport("B_IE_Operation_Data");
            frm.ShowDialog();
            //InitializeForm();
            base.DoImport(sender);
        }
        private void FrmBIEOperationData_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (!string.IsNullOrEmpty(drawNum))
            {
                string sql = "";
                sql = @"update B_IE_SJData_Import set locked=0 where DRAWING_NO_STANDARD='" + drawNum + "'";
                int m = BaseBuildSql.ExecuteNonQuery(sql);
            }
        }
    }
}
